﻿using KayakMes.Common;
using KayakMes.Common.Result;
using KayakMes.RBAC.Application.Input;
using KayakMes.RBAC.Application.OUT;
using KayakMes.RBAC.Doamin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Yitter.IdGenerator;
using NPOI.SS.UserModel;
using System.IO;
using NPOI.XSSF.UserModel;
using NPOI.SS.Util;


namespace KayakMes.RBAC.Application.Login
{
    public class UserService : IUserService
    {
        private readonly BaseReposiotry<UserModel> _userRepo;

        public UserService(BaseReposiotry<UserModel> userRepo)
        {
            _userRepo = userRepo;
        }
        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ApiResult<int> AddUser(AddUserInput input)
        {
          ApiResult<int> apiResult = new ApiResult<int>();
            var model = new UserModel
            {
                Id = YitIdHelper.NextId(),
                 CreateTime = DateTime.Now,
                UserCodes = input.UserCode,
                UserName = input.UserName,
                Password = ComputeMd5Hash(input.Password),
                UserShortName = input.UserShortName,
                Phone = input.Phone,
                UserType = input.UserType,
                Email = input.Email


            };
            var result = _userRepo.Add(model);
            if (result > 0)
            {
                apiResult.Code = ApiEnums.Success;
                apiResult.Message = "添加用户成功";
                apiResult.Data = result;
            }
            else
            {
                apiResult.Code = ApiEnums.Fail;
                apiResult.Message = "添加用户失败";
                apiResult.Data = 0;
            }
            return apiResult;

        }
        /// <summary>
        /// 获取所有用户
        /// </summary>
        /// <param name="input">分页查询参数</param>
        /// <returns>分页结果</returns>
        public ApiPaging<UserDTO> GetUserAll(GetUserInput input)
        {
            try
            {
                // 构建基础查询
                var query = _userRepo.GetAll();

                // 添加查询条件
                if (!string.IsNullOrWhiteSpace(input.UserCode))
                {
                    query = query.Where(u => u.UserCodes.Contains(input.UserCode));
                }

                if (!string.IsNullOrWhiteSpace(input.UserName))
                {
                    query = query.Where(u => u.UserName.Contains(input.UserName));
                }

                // 获取总记录数
                var total = query.Count();

                // 执行分页查询
                var users = query.OrderByDescending(u => u.CreateTime)
                                .Skip((input.PageIndex - 1) * input.PageSize)
                                .Take(input.PageSize)
                                .ToList();

                // 转换为DTO
                var userDtos = users.Select(u => new UserDTO
                {
                   
                    UserCodes = u.UserCodes,
                    UserName = u.UserName,
                    UserShortName = u.UserShortName,
                    Phone = u.Phone,
                    UserType = u.UserType,
                    Email = u.Email,
                    
                }).ToList();

                // 返回分页结果
                return new ApiPaging<UserDTO>
                {
                    Items = userDtos,
                    Total = total,
                    PageIndex = input.PageIndex,
                    PageSize = input.PageSize
                };
            }
            catch (Exception ex)
            {
                throw new Exception($"获取用户列表失败：{ex.Message}");
            }
        }
        /// <summary>
        /// 获取用户详情
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>

        public ApiResult<UserModel> GetUserModel(long Id)
        {
            ApiResult<UserModel> apiResult = new ApiResult<UserModel>();
            var model = _userRepo.GetModel(Id);
            if (model == null)
            {
                apiResult.Code = ApiEnums.Fail;
                apiResult.Message = "查询失败";
            }
            else
            {
                apiResult.Code = ApiEnums.Success;
                apiResult.Message = "查询成功";
                apiResult.Data = model;
            }
            return apiResult;
        }

        public ApiResult<UserModel> Login(LoginInput input)
        {
            // 1. 查找用户
            var user = _userRepo.GetAll().First(x => x.UserName == input.UserName);
            if (user == null)
            {
                return new ApiResult<UserModel> { Code = ApiEnums.Fail, Message = "用户不存在" };
            }

            // 2. 校验密码（MD5加密比对）
            var hashedPassword = ComputeMd5Hash(input.Password);
            if (user.Password != hashedPassword)
            {
                return new ApiResult<UserModel> { Code = ApiEnums.Fail, Message = "密码错误" };
            }

            // 3. 返回成功结果
            return new ApiResult<UserModel>
            {
                Code = ApiEnums.Success,
                Message = "登录成功",
                Data = user
            };
        }
     
        

        // MD5加密方法
        public string ComputeMd5Hash(string rawData)
        {
            using (MD5 md5Hash = MD5.Create())
            {
                byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(rawData));
                StringBuilder sBuilder = new StringBuilder();
                for (int i = 0; i < data.Length; i++)
                {
                    sBuilder.Append(data[i].ToString("x2"));
                }
                return sBuilder.ToString();
            }
        }

        /// <summary>
        /// 导出用户列表
        /// </summary>
        /// <returns>返回Excel文件字节数组</returns>
        public async Task<ApiResult<byte[]>> Userexport()
        {
            try
            {
                // 获取所有用户数据
                var users = _userRepo.GetAll().ToList();

                // 创建工作簿
                using IWorkbook workbook = new XSSFWorkbook();
                ISheet sheet = workbook.CreateSheet("用户列表");

                #region 设置样式
                // 设置表头样式
                ICellStyle headerStyle = workbook.CreateCellStyle();
                IFont headerFont = workbook.CreateFont();
                headerFont.IsBold = true;
                headerFont.FontName = "宋体";
                headerFont.FontHeightInPoints = 12;
                headerStyle.SetFont(headerFont);
                headerStyle.Alignment = HorizontalAlignment.Center;
                headerStyle.VerticalAlignment = VerticalAlignment.Center;
                headerStyle.BorderTop = BorderStyle.Thin;
                headerStyle.BorderBottom = BorderStyle.Thin;
                headerStyle.BorderLeft = BorderStyle.Thin;
                headerStyle.BorderRight = BorderStyle.Thin;
                headerStyle.FillForegroundColor = IndexedColors.Grey25Percent.Index;
                headerStyle.FillPattern = FillPattern.SolidForeground;

                // 设置数据样式
                ICellStyle dataStyle = workbook.CreateCellStyle();
                IFont dataFont = workbook.CreateFont();
                dataFont.FontName = "宋体";
                dataFont.FontHeightInPoints = 11;
                dataStyle.SetFont(dataFont);
                dataStyle.Alignment = HorizontalAlignment.Center;
                dataStyle.VerticalAlignment = VerticalAlignment.Center;
                dataStyle.BorderTop = BorderStyle.Thin;
                dataStyle.BorderBottom = BorderStyle.Thin;
                dataStyle.BorderLeft = BorderStyle.Thin;
                dataStyle.BorderRight = BorderStyle.Thin;

                // 设置日期格式样式
                ICellStyle dateStyle = workbook.CreateCellStyle();
                dateStyle.CloneStyleFrom(dataStyle);
                IDataFormat dataFormat = workbook.CreateDataFormat();
                dateStyle.DataFormat = dataFormat.GetFormat("yyyy-MM-dd HH:mm:ss");
                #endregion

                #region 创建表头
                string[] headers = new string[] 
                { 
                    "用户ID", "用户编号", "用户名", "用户简称", 
                    "手机号", "用户类型", "邮箱", "创建时间"
                };
                
                IRow headerRow = sheet.CreateRow(0);
                headerRow.Height = 30 * 20; // 设置行高
                
                for (int i = 0; i < headers.Length; i++)
                {
                    ICell cell = headerRow.CreateCell(i);
                    cell.SetCellValue(headers[i]);
                    cell.CellStyle = headerStyle;
                    // 设置列宽
                    sheet.SetColumnWidth(i, 20 * 256);
                }
                #endregion

                #region 填充数据
                int rowIndex = 1;
                foreach (var user in users)
                {
                    IRow dataRow = sheet.CreateRow(rowIndex++);
                    dataRow.Height = 25 * 20; // 设置数据行高
                    
                    // 设置单元格值
                    SetCellValue(dataRow.CreateCell(0), user.Id, dataStyle);
                    SetCellValue(dataRow.CreateCell(1), user.UserCodes, dataStyle);
                    SetCellValue(dataRow.CreateCell(2), user.UserName, dataStyle);
                    SetCellValue(dataRow.CreateCell(3), user.UserShortName, dataStyle);
                    SetCellValue(dataRow.CreateCell(4), user.Phone, dataStyle);
                    SetCellValue(dataRow.CreateCell(5), user.UserType, dataStyle);
                    SetCellValue(dataRow.CreateCell(6), user.Email, dataStyle);
                    
                    // 设置日期格式的单元格
                    var dateCell = dataRow.CreateCell(7);
                    dateCell.SetCellValue(user.CreateTime);
                    dateCell.CellStyle = dateStyle;
                }
                #endregion

                // 转换为字节数组
                using (MemoryStream ms = new MemoryStream())
                {
                    workbook.Write(ms);
                    return new ApiResult<byte[]>
                    {
                        Code = ApiEnums.Success,
                        Message = "导出成功",
                        Data = ms.ToArray()
                    };
                }
            }
            catch (Exception ex)
            {
                return new ApiResult<byte[]>
                {
                    Code = ApiEnums.Fail,
                    Message = $"导出失败：{ex.Message}"
                };
            }
        }

        /// <summary>
        /// 设置单元格值并应用样式
        /// </summary>
        private void SetCellValue(ICell cell, object value, ICellStyle style)
        {
            if (value != null)
            {
                cell.SetCellValue(value.ToString());
            }
            else
            {
                cell.SetCellValue("");
            }
            cell.CellStyle = style;
        }
    }
}
